package com.friend.joey.applicationfriend;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.speech.RecognitionListener;
import android.speech.SpeechRecognizer;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.ashokvarma.bottomnavigation.utils.Utils;
import com.baidu.speech.VoiceRecognitionService;
import com.baidu.trace.api.fence.CreateFenceResponse;
import com.baidu.trace.api.fence.DeleteFenceResponse;
import com.baidu.trace.api.fence.FenceListResponse;
import com.baidu.trace.api.fence.HistoryAlarmResponse;
import com.baidu.trace.api.fence.MonitoredStatusByLocationResponse;
import com.baidu.trace.api.fence.MonitoredStatusResponse;
import com.baidu.trace.api.fence.UpdateFenceResponse;
import com.baidu.trace.model.PushMessage;
import com.friend.joey.applicationfriend.ChildActivities.ChildTalkActivity;
import com.friend.joey.applicationfriend.Classes.AlertMessage;
import com.friend.joey.applicationfriend.Classes.Constant;
import com.friend.joey.applicationfriend.Classes.JSONRequest;
import com.friend.joey.applicationfriend.Classes.Msgtalk;
import com.friend.joey.applicationfriend.Classes.RememRecord;
import com.friend.joey.applicationfriend.Classes.TimeDeal;
import com.friend.joey.applicationfriend.Database.MyDatabaseHelper;
import com.friend.joey.applicationfriend.Fragments.FragmentForget;
import com.friend.joey.applicationfriend.Fragments.FragmentFriend;
import com.friend.joey.applicationfriend.Fragments.FragmentHealth;
import com.friend.joey.applicationfriend.Fragments.FragmentSearch;
import com.friend.joey.applicationfriend.Fragments.FragmentTalk;
import com.friend.joey.applicationfriend.OldAcitivities.TimePupupWindow;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;

/**
 * Created by Joey on 2017/4/20.
 */

public class MainActivity extends AppCompatActivity implements BottomNavigationBar.OnTabSelectedListener,RecognitionListener{

    //数据管理
    public SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private MyDatabaseHelper dbHelper;//数据库
    private SQLiteDatabase db;
    //状态标识
    public Boolean isLogin;
    public int theme=0;
    private int setTheme=0;
    private boolean setTraceServer;
    private boolean TraceServerState;
    private boolean firstTrace;
    private boolean hasPop=false;
    private boolean isBDRstart=false;//识别开始
    private boolean isSucced=false;//识别成功
    //底部导航栏与其他功能页面
    private BottomNavigationBar bottomNavigationBar;
    private FragmentManager mFragmentManager;
    private FragmentTalk mFragmentTalk;
    private FragmentForget mFragmentForget;
    private FragmentFriend mFragmentFriend;
    private FragmentHealth mFragmentHealth;
    private FragmentSearch mFragmentSearch;
    private FragmentTransaction transaction;
    private int lastSelectedPosition;
    //悬浮按钮
    private FloatingActionButton fab;
    private int locationForFab;//悬浮按键触摸位置标识
    //侧边栏
    private DrawerLayout mDrawerLayout;
    private MenuItem itemblue;
    private MenuItem itemgreen;
    private MenuItem itemTrace;
    private NavigationView navView;
    private View navheader;
    //其他控件
    private TextView voice_result;
    private TimePupupWindow pupupWindow;
    public InputMethodManager imm;
    //语音识别
    private SpeechRecognizer speechRecognizer;//语音识别
    //轨迹监控服务
    private TraceRecord traceRecord;
    public int back=0;
    //与服务器交互
    private String sendtxt;
    private TimeDeal timedeal;
    //交互handler
    private MyHandler mHandler;
    //闹钟相关
    private AlarmManager manager;

    private class MyHandler extends Handler {
        private WeakReference<MainActivity> mWeakReference;
        public MyHandler(MainActivity activity){
            mWeakReference=new WeakReference<MainActivity>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity activity= mWeakReference.get();
            if(activity!=null){
                switch(msg.what){
                    case 1:
                        if(!"".equals(msg.obj.toString())){
                            Msgtalk rmsg = new Msgtalk(msg.obj.toString(), Msgtalk.TYPE_RECEIVED);
                            mFragmentTalk.insertMsgs(rmsg);
                            //mFragmentTalk.insertIntoDatabase(rmsg);
                            insertIntoDatabase(rmsg);
                            if(lastSelectedPosition==0){
                                mFragmentTalk.speakBD(msg.obj.toString());
                            }
                        }
                        break;
                    case 2:
                        Toast.makeText(activity,msg.obj.toString(), Toast.LENGTH_SHORT).show();
                        break;
                    case -1:
                        //Toast.makeText(activity, "失败", Toast.LENGTH_SHORT).show();
                        break;
                    case 10:
                        Toast.makeText(MainActivity.this,"打包回传:"+msg.obj.toString(), Toast.LENGTH_SHORT).show();
                        NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
                        Notification notification=new NotificationCompat.Builder(getApplicationContext())
                                .setContentTitle("地理围栏")
                                .setContentText(msg.obj.toString())
                                .setWhen(System.currentTimeMillis())
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                                .build();
                        manager.notify(1,notification);
                        break;
                    default:
                        Toast.makeText(activity, "没有信息", Toast.LENGTH_SHORT).show();
                }
            }
            else{
                Toast.makeText(activity, "错误", Toast.LENGTH_SHORT).show();
            }
        }
    }
    private TraceService.TraceServiceBinder traceBinder;
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            traceBinder=(TraceService.TraceServiceBinder)iBinder;
            traceBinder.setTraceServiceListener(new TraceService.TraceServiceListener() {
                @Override
                public void onBack(int state,int status, String s) {
                    Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
                    if(state==TraceService.GATHER_OFF && status==0){
                        itemTrace.setTitle("轨迹监控：关");
                        TraceServerState=false;
                    }
                    if(state==TraceService.GATHER_ON && status==0){
                        itemTrace.setTitle("轨迹监控：开");
                        TraceServerState=true;
                    }
                }
            });

            if(setTraceServer) {
                if(traceBinder.getProgress()==TraceService.TRACE_ON){
                    TraceServerState=true;
                    firstTrace=false;
                    itemTrace.setTitle("轨迹监控：开");
                }else{
                    TraceServerState=false;
                    firstTrace=true;
                    itemTrace.setTitle("轨迹服务未开启");
                }
            }else{
                firstTrace=false;
            }
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Toast.makeText(MainActivity.this,"unBind",Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pref= PreferenceManager.getDefaultSharedPreferences(this);
        isLogin=pref.getBoolean("islogin",false);
        setTraceServer=pref.getBoolean("setTraceServer",false);
        TraceServerState=setTraceServer;
        theme=pref.getInt("theme",0);
        setTheme=theme;
        switch(theme){
            case 0:
                setTheme(R.style.AppTheme);
                break;
            case 2:
                setTheme(R.style.GreenTheme);
                break;
        }
        setContentView(R.layout.activity_main);
        mHandler = new MyHandler(this);
        voice_result=(TextView)findViewById(R.id.voice_result);

        //悬浮按钮相关
        fab=(FloatingActionButton)findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view){}
        });
        fab.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Toast.makeText(MainActivity.this,"longclicked", Toast.LENGTH_SHORT).show();
                if(!hasPop) {
                    pupupWindow = new TimePupupWindow(LayoutInflater.from(MainActivity.this), getWindow().getDecorView(), TimePupupWindow.ALERTPOP);
                    hasPop=true;
                }
                FabDown();
                return false;
            }
        });
        fab.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                int x,y;
                switch(motionEvent.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        //Toast.makeText(MainActivity.this,"down", Toast.LENGTH_SHORT).show();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if(hasPop) {
                            x = (int) motionEvent.getRawX();
                            y = (int) motionEvent.getRawY();
                            if (!isTouchPointInView(fab, x, y)) {
                                locationForFab=TimePupupWindow.STATEOUT;
                                pupupWindow.changeState(TimePupupWindow.STATEOUT);
                            } else {
                                //voice_result.setText("里面");
                                locationForFab=TimePupupWindow.STATEIN;
                                pupupWindow.changeState(TimePupupWindow.STATEIN);
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        //Toast.makeText(MainActivity.this,"up", Toast.LENGTH_SHORT).show();
                        if(hasPop) {
                            pupupWindow.closePopupWindow();
                            hasPop=false;
                        }
                        x = (int) motionEvent.getRawX();
                        y = (int) motionEvent.getRawY();
                        if (!isTouchPointInView(fab, x, y)) {
                            //Toast.makeText(MainActivity.this,"outside", Toast.LENGTH_SHORT).show();
                            if(lastSelectedPosition==0){
                                mFragmentTalk.setInputText("");
                            }
                            isSucced=false;
                        }else{
                            //Toast.makeText(MainActivity.this,"inside", Toast.LENGTH_SHORT).show();
                            if(lastSelectedPosition==0 && isSucced){
                                mFragmentTalk.ClickSend();
                            }
                            isSucced=false;
                        }
                        FabUp();
                        break;
                }
                return false;
            }
        });
        //底部导航栏
        bottomNavigationBar = (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar);
        initBottomNavigationBar();
        lastSelectedPosition=0;
        onTabSelected(lastSelectedPosition);

        // 创建识别器与注册监听器
        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this, new ComponentName(this, VoiceRecognitionService.class));
        speechRecognizer.setRecognitionListener(this);
        //键盘
        imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
        //侧边栏相关
        mDrawerLayout=(DrawerLayout)findViewById(R.id.activity_main);
        navView=(NavigationView)findViewById(R.id.nav_view);
        itemblue=navView.getMenu().findItem(R.id.blue);
        itemgreen= navView.getMenu().findItem(R.id.green);
        itemTrace=navView.getMenu().findItem(R.id.Trace);
        navheader=navView.inflateHeaderView(R.layout.nav_header);


        Intent bindIntent = new Intent(MainActivity.this,TraceService.class);
        bindService(bindIntent,connection,BIND_AUTO_CREATE);

        if(!setTraceServer){
            itemTrace.setTitle("轨迹监控：关");
        }
        navView.setCheckedItem(R.id.changeTheme);
        navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                //Toast.makeText(MainActivity.this,"选中"+item.getTitle()+" "+item.getItemId(),Toast.LENGTH_SHORT).show();
                switch(item.getItemId()){
                    case R.id.loginOut:
                        ChangeLogin();
                        break;
                    case R.id.changeTheme:
                        if(!itemgreen.isVisible()){
                            itemgreen.setVisible(true);
                            itemblue.setVisible(true);
                        }else{
                            itemgreen.setVisible(false);
                            itemblue.setVisible(false);
                        }
                        break;
                    case R.id.green:
                        ChangeTheme(2);
                        break;
                    case R.id.blue:
                        ChangeTheme(0);
                        break;
                    case R.id.Map:
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.POSITION");
                        startActivity(intent);
                        break;
                    case R.id.Trace:
                        ChangeTraceSet();
                        break;
                }
                //mDrawerLayout.closeDrawers();//关闭滑动菜单
                return true;
            }
        });


        //向服务器端发送时间数据
        SendTimejson();
        ////开启轨迹服务
        traceRecord = new TraceRecord("myTrace", getApplicationContext());
        traceRecord.setOnTraceListener(new TraceRecord.onTraceListener() {
            @Override
            public void onMBindServiceCallback(int i, String s) {

            }
            @Override
            public void onMStartTraceCallback(int status, String message){

            }
            @Override
            public void onMStopTraceCallback(int status, String message) {

            }
            @Override
            public void onMStartGatherCallback(int status, String message) {

            }
            @Override
            public void onMStopGatherCallback(int status, String message) {
                Toast.makeText(MainActivity.this, "停止采集:" + Integer.toString(status) + message.toString(), Toast.LENGTH_SHORT).show();

            }
            @Override
            public void onMPushCallback(byte messageNo, PushMessage message) {
                back++;
                Message message2 = mHandler.obtainMessage();
                message2.what = 10;
                message2.obj=message;
                mHandler.sendMessage(message2);
            }
        });
        traceRecord.setOnFenceListener(new TraceRecord.onFenceListener() {
            @Override
            public void onCreateFenceCallback(CreateFenceResponse response) {
                //Toast.makeText(MainActivity.this, "创建围栏:" + response.toString(), Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onUpdateFenceCallback(UpdateFenceResponse response) {
                if(response.getStatus()!=0) {
                    Toast.makeText(MainActivity.this, "更新围栏失败:" + response.toString(), Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this, "更新围栏成功", Toast.LENGTH_SHORT).show();
                }
                //voice_result.setText(response.toString());
            }
            @Override
            public void onDeleteFenceCallback(DeleteFenceResponse response) {
                //Toast.makeText(MainActivity.this, "删除围栏:" + response.toString(), Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onFenceListCallback(FenceListResponse response) {
                //voice_result.setText(response.toString());
            }
            @Override
            public void onMonitoredStatusCallback(MonitoredStatusResponse response) {

            }
            @Override
            public void onMonitoredStatusByLocationCallback(MonitoredStatusByLocationResponse response) {

            }
            @Override
            public void onHistoryAlarmCallback(HistoryAlarmResponse response) {

            }
        });
        traceRecord.updateFence();
        //闹钟相关
        manager=(AlarmManager)getSystemService(ALARM_SERVICE);
    }

    ////底部导航栏相关函数
    public void initBottomNavigationBar(){
        bottomNavigationBar.setTabSelectedListener(this);
        bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_RIPPLE);
        bottomNavigationBar.setAutoHideEnabled(true);
        bottomNavigationBar.addItem(new BottomNavigationItem(R.drawable.bottomtalk, "聊天"))
                .addItem(new BottomNavigationItem(R.drawable.bottomforget, "备忘"))
                .addItem(new BottomNavigationItem(R.drawable.bottomhealth,"子女"))
                .addItem(new BottomNavigationItem(R.drawable.bottomsearch, "搜索"))
                .addItem(new BottomNavigationItem(R.drawable.bottommusic, "音乐"))
                .setFirstSelectedPosition(0)
                .initialise();
    }
    @Override
    public void onTabSelected(int position) {
        //开启事务
        mFragmentManager = getSupportFragmentManager();
        transaction = mFragmentManager.beginTransaction();
        if(theme!=setTheme){
            clearFragemnt(transaction,0);
            theme=setTheme;
        }
        hideFragment(transaction, 0);
        switch (position){
            case 0:
                if(mFragmentTalk == null){
                    mFragmentTalk = FragmentTalk.newInstance("FragmentTalk");
                    transaction.add(R.id.main_place, mFragmentTalk);
                } else {
                    transaction.show(mFragmentTalk);
                }
                showFab();
                voice_result.setText("");
                break;
            case 1:
                if(mFragmentForget  == null){
                    mFragmentForget = FragmentForget.newInstance("FragmentForget");
                    transaction.add(R.id.main_place, mFragmentForget);
                } else {
                    transaction.show(mFragmentForget);
                }
                hideFab();
                voice_result.setText("");
                break;
            case 2:
                if(mFragmentHealth == null){
                    mFragmentHealth= FragmentHealth.newInstance("FragmentHealth");
                    transaction.add(R.id.main_place, mFragmentHealth);
                } else {
                    transaction.show(mFragmentHealth);
                }
                showFab();
                voice_result.setText("");
                break;
            case 3:
                if(mFragmentSearch == null){
                    mFragmentSearch = FragmentSearch.newInstance("FragmentSearch");
                    transaction.add(R.id.main_place, mFragmentSearch);
                } else {
                    transaction.show(mFragmentSearch);
                }
                showFab();
                voice_result.setText("");
                break;
            case 4:
                if(mFragmentFriend == null){
                    mFragmentFriend = FragmentFriend.newInstance("FragmentFriend");
                    transaction.add(R.id.main_place, mFragmentFriend);
                } else {
                    transaction.show(mFragmentFriend);
                }
                hideFab();
                voice_result.setText("");
                break;
            default:
                break;
        }
        lastSelectedPosition = position;
        transaction.commit();
    }
    @Override
    public void onTabUnselected(int position) {

    }
    @Override
    public void onTabReselected(int position) {

    }
    private void hideFragment(FragmentTransaction transaction, int flag){
        if(mFragmentTalk != null && flag == 0){
            transaction.hide(mFragmentTalk);
        }
        if(mFragmentForget != null && flag == 0){
            transaction.hide(mFragmentForget);
        }
        if(mFragmentHealth != null && flag == 0){
            transaction.hide(mFragmentHealth);
        }
        if(mFragmentSearch != null && flag == 0){
            transaction.hide(mFragmentSearch);
        }
        if(mFragmentFriend != null && flag == 0){
            transaction.hide(mFragmentFriend);
        }
    }
    private void clearFragemnt(FragmentTransaction transaction, int position){
        Toast.makeText(this,"删除全部fragments",Toast.LENGTH_SHORT).show();
        if(mFragmentTalk != null){
            transaction.remove(mFragmentTalk);
            mFragmentTalk=null;
        }
        if(mFragmentForget != null){
            transaction.remove(mFragmentForget);
            mFragmentForget=null;
        }
        if(mFragmentHealth != null){
            transaction.remove(mFragmentHealth);
            mFragmentHealth=null;
        }
        if(mFragmentSearch != null){
            transaction.remove(mFragmentSearch);
            mFragmentSearch=null;
        }
        if(mFragmentFriend != null){
            transaction.remove(mFragmentFriend);
            mFragmentFriend=null;
        }
    }
    //悬浮按钮相关函数
    public void hideFab(){
        fab.setVisibility(FloatingActionButton.INVISIBLE);
    }
    public void showFab(){
        fab.setVisibility(FloatingActionButton.VISIBLE);
    }
    private boolean isTouchPointInView(View view, int x, int y) {
        if (view == null) {
            return false;
        }
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int left = location[0];
        int top = location[1];
        int right = left + view.getMeasuredWidth();
        int bottom = top + view.getMeasuredHeight();
        if (y >= top && y <= bottom && x >= left
                && x <= right) {
            return true;
        }
        return false;
    }
    public void FabDown(){
        speechRecognizer.cancel();
        voice_result.setText("取消上次录音");
        startASR();
    }
    private void FabUp(){
        if(isBDRstart) {
            speechRecognizer.stopListening();
            isBDRstart=false;
            //isSucced=false;
            Toast.makeText(MainActivity.this,"未结束，取消录音", Toast.LENGTH_SHORT).show();
        }
    }
    //侧边栏相关函数
    public void showDrawer(){
        mDrawerLayout.openDrawer(GravityCompat.START);
    }
    private void ChangeTheme(int changetheme){
        //Toast.makeText(MainActivity.this,"修改"+Integer.toString(setTheme)+Integer.toString(lastSelectedPosition),Toast.LENGTH_SHORT).show();
        setTheme=changetheme;
        editor=pref.edit();
        editor.putInt("theme",setTheme);
        editor.commit();
        switch(setTheme){
            case 0:
                setTheme(R.style.AppTheme);
                break;
            case 2:
                setTheme(R.style.GreenTheme);
                break;
        }
        onTabSelected(lastSelectedPosition);

        if(navheader==null){}else{
            int BackColor=Utils.fetchContextColor(this, R.attr.colorPrimary);
            navheader.setBackgroundColor(BackColor);
            bottomNavigationBar.clearAll();
            bottomNavigationBar.setActiveColor(String.format("#%06X", BackColor));
            bottomNavigationBar.addItem(new BottomNavigationItem(R.drawable.bottomtalk, "聊天"))
                    .addItem(new BottomNavigationItem(R.drawable.bottomforget, "备忘"))
                    .addItem(new BottomNavigationItem(R.drawable.bottomhealth,"健康"))
                    .addItem(new BottomNavigationItem(R.drawable.bottomsearch, "搜索"))
                    .addItem(new BottomNavigationItem(R.drawable.bottommusic, "好友"))
                    .setFirstSelectedPosition(0)
                    .initialise();
        }
    }
    private void ChangeLogin(){
        if(isLogin) {
            editor=pref.edit();
            editor.putBoolean("islogin",false);
            editor.putInt("theme",0);
            editor.commit();

            unbindService(connection);
            Intent stopIntent=new Intent(MainActivity.this,TraceService.class);
            stopService(stopIntent);
            isLogin=false;

            Intent intent = new Intent();
            intent.setAction("com.friend.joey.LOGIN");
            startActivity(intent);
            finish();

            //Toast.makeText(MainActivity.this,"登陆",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(MainActivity.this,"未登陆",Toast.LENGTH_SHORT).show();
        }
    }
    private void ChangeTraceSet(){
        //Toast.makeText(MainActivity.this,Boolean.toString(setTraceServer)+Boolean.toString(TraceServerState),Toast.LENGTH_SHORT).show();
        if(setTraceServer==TraceServerState) {
            if (setTraceServer) {
                traceBinder.stopGather();
                editor = pref.edit();
                setTraceServer = false;
                editor.putBoolean("setTraceServer", false);
                editor.commit();
                //Toast.makeText(MainActivity.this,Boolean.toString(setTraceServer)+Boolean.toString(TraceServerState),Toast.LENGTH_SHORT).show();
            } else {
                setTraceServer = true;
                if(traceBinder.getProgress()==TraceService.TRACE_OFF){
                    Intent startIntent = new Intent(MainActivity.this, TraceService.class);
                    startIntent.putExtra("entityName", "myTrace");
                    startIntent.putExtra("gather", setTraceServer);
                    startService(startIntent);
                }else{
                    traceBinder.startGather(true);
                }
                editor = pref.edit();
                editor.putBoolean("setTraceServer", true);
                editor.commit();
                //Toast.makeText(MainActivity.this,Boolean.toString(setTraceServer)+Boolean.toString(TraceServerState),Toast.LENGTH_SHORT).show();
            }
        }else if(firstTrace){
            firstTrace=false;
            Intent startIntent = new Intent(MainActivity.this, TraceService.class);
            startIntent.putExtra("entityName", "myTrace");
            startIntent.putExtra("gather", setTraceServer);
            startService(startIntent);
        }
    }
    // 语音识别部分
    void startASR() {
        voice_result.setText("请等待...");
        Intent intent = new Intent();
        bindParams(intent);
        speechRecognizer.startListening(intent);
        isBDRstart=true;
        isSucced=false;
    }
    void bindParams(Intent intent) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        if (sp.getBoolean("tips_sound", true)) {
            //Toast.makeText(MainActivity.this,"true", Toast.LENGTH_SHORT).show();
            intent.putExtra(Constant.EXTRA_SOUND_START, R.raw.bdspeech_recognition_start);
            intent.putExtra(Constant.EXTRA_SOUND_END, R.raw.bdspeech_speech_end);
            intent.putExtra(Constant.EXTRA_SOUND_SUCCESS, R.raw.bdspeech_recognition_success);
            intent.putExtra(Constant.EXTRA_SOUND_ERROR, R.raw.bdspeech_recognition_error);
            intent.putExtra(Constant.EXTRA_SOUND_CANCEL, R.raw.bdspeech_recognition_cancel);
            intent.putExtra(Constant.EXTRA_SAMPLE,16000);
            intent.putExtra(Constant.EXTRA_LANGUAGE,"cmn-Hans-CN");
            intent.putExtra(Constant.EXTRA_NLU,"enable");

            //intent.putExtra(Constant.EXTRA_OFFLINE_LM_RES_FILE_PATH, "/sdcard1/afriend/s_1.txt");
            //intent.putExtra(Constant.EXTRA_OFFLINE_ASR_BASE_FILE_PATH, "/sdcard/easr/s_1");
        }
    }
    @Override
    public void onReadyForSpeech(Bundle bundle) {
        //Toast.makeText(MainActivity.this,"onReadyForSpeech", Toast.LENGTH_SHORT).show();
        voice_result.setText("请说话");
    }
    @Override
    public void onBeginningOfSpeech() {
        //Toast.makeText(MainActivity.this,"onBeginningOfSpeech", Toast.LENGTH_SHORT).show();
        voice_result.setText("开始说话，倾听中...");
    }
    @Override
    public void onRmsChanged(float v) {
        //Toast.makeText(MainActivity.this,Float.toString(v), Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onBufferReceived(byte[] bytes) {
        //Toast.makeText(MainActivity.this,"onBufferReceived", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onEndOfSpeech() {
        //Toast.makeText(MainActivity.this,"onEndOfSpeech", Toast.LENGTH_SHORT).show();
        voice_result.setText("说话结束，识别中..");
    }
    @Override
    public void onError(int i) {
        //Toast.makeText(MainActivity.this,Integer.toString(i), Toast.LENGTH_SHORT).show();
        voice_result.setText("识别失败");
        isBDRstart=false;
        pupupWindow.changeState(TimePupupWindow.STATEFAIL);
        Toast.makeText(MainActivity.this,"ERROR", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onResults(Bundle bundle) {
        //Toast.makeText(MainActivity.this,bundle.toString(), Toast.LENGTH_LONG).show();
        if(locationForFab==TimePupupWindow.STATEIN){
            pupupWindow.changeState(TimePupupWindow.STATEFINISHIN);
        }else if(locationForFab==TimePupupWindow.STATEOUT){
            pupupWindow.changeState(TimePupupWindow.STATEFINISHOUT);
        }
        if(isBDRstart) {
            String result = bundle.getStringArrayList("results_recognition").toString();
            String result1 = result.substring(1, result.length() - 1);
            voice_result.setText(result1);
            isBDRstart = false;
            isSucced = true;
            if (lastSelectedPosition == 0) {
                mFragmentTalk.setInputText(result1);
            }else if(lastSelectedPosition == 2){
                mFragmentHealth.setTextInput(result1);
            }else if(lastSelectedPosition == 3){
                mFragmentSearch.setTxt_cInput(result1);
            }

        }
    }
    @Override
    public void onPartialResults(Bundle bundle) {
        //Toast.makeText(MainActivity.this,"onPartialResults", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onEvent(int i, Bundle bundle) {
        //Toast.makeText(MainActivity.this,"onEvent", Toast.LENGTH_SHORT).show();
        switch (i) {
            case 11: // eventType == 11 表是返回详细错误信息
                String reason = bundle.get("reason") + "";
                Toast.makeText(MainActivity.this,"EVENT_ERROR," + reason, Toast.LENGTH_SHORT).show();
                voice_result.setText("EVENT_ERROR," + reason);
                break;
        }
    }
    //*******语音识别部分结束

    //与服务器的json处理
    public JSONObject Sendjson(JSONObject jsonobj,String function){
        //String url= "http://10.242.90.85:8000/appstart";
        String url= "http://10.242.90.85:8000/"+function;
        JSONRequest test1=new JSONRequest(jsonobj,url);
        JSONObject resultobj= test1.jsonRequest();
        return resultobj;
    }
    public void SendTimejson(){
        timedeal = new TimeDeal(TimeDeal.INITDATE);
        String time=timedeal.GetTimeString();
        //Toast.makeText(MainActivity.this,"发送信息给服务端："+time, Toast.LENGTH_SHORT).show();
        //线程进行json请求
        sendtxt=time;
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run(){
                JSONObject timeobj=new JSONObject();
                try {
                    timeobj.put("text",sendtxt);
                    timeobj.put("time",timedeal);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                GetTimejson(Sendjson(timeobj,"appstart"));
            }
        });
        thread.start();
    }
    public void GetTimejson(JSONObject resultobj){
        //Toast.makeText(MainActivity.this,"尝试获取答案", Toast.LENGTH_SHORT).show();
        Message message = mHandler.obtainMessage();
        message.what=-1;
        try {
            message.obj = resultobj.getString("result");
            message.what=1;
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            message.what=-1;
        }
        mHandler.sendMessage(message);
    }
    //********数据操作相关
    //插入聊天信息
    public void insertIntoDatabase(Msgtalk msg){
        dbHelper = new MyDatabaseHelper(MainActivity.this,"TestTalk.db",null,2);//数据库
        db=dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("txt",msg.getContent());
        values.put("side",msg.getType());
        long i= db.insert("talk",null,values);
        Toast.makeText(MainActivity.this,"添加消息："+Long.toString(i), Toast.LENGTH_SHORT).show();
        db.close();
    }
    public void insertIntoDatabase(RememRecord rem){
        Toast.makeText(MainActivity.this,"添加备忘", Toast.LENGTH_SHORT).show();
        dbHelper = new MyDatabaseHelper(MainActivity.this,"TestTalk.db",null,2);//数据库
        db=dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title",rem.getTitle());
        values.put("content",rem.getContent());
        values.put("addtime",rem.getAddtime());
        values.put("id",rem.getId());
        int type=rem.getType();
        values.put("type",type);
        if(type==RememRecord.SET_ALERT) {
            values.put("alerttime", rem.getAlerttime());
            values.put("addid", rem.getalertId());
        }
        long i=db.insert("forget",null,values);
        //Toast.makeText(MainActivity.this,"添加备忘"+Long.toString(i), Toast.LENGTH_SHORT).show();
        db.close();
    }
    public void insertIntoDatabase(AlertMessage alert){
        dbHelper = new MyDatabaseHelper(MainActivity.this,"TestTalk.db",null,2);//数据库
        db=dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title",alert.getTitle());
        values.put("content",alert.getContent());
        values.put("time",alert.getTime());
        values.put("type",alert.getType());
        values.put("id",alert.getId());
        long i=db.insert("message",null,values);
        Toast.makeText(MainActivity.this,"添加子女提醒"+Long.toString(i), Toast.LENGTH_SHORT).show();
        //Toast.makeText(MainActivity.this,"添加备忘"+Long.toString(i), Toast.LENGTH_SHORT).show();
        db.close();
    }
    public void insertIntoFamilyDatabase(Msgtalk smsg){
        dbHelper = new MyDatabaseHelper(MainActivity.this,"TestTalk.db",null,2);//数据库
        db=dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("txt",smsg.getContent());
        values.put("side",smsg.getType());
        long i= db.insert("talkchild",null,values);
        Toast.makeText(MainActivity.this,"添加家庭消息："+Long.toString(i), Toast.LENGTH_SHORT).show();
        db.close();
    }
    public void insertIntoFriendDatabase(Msgtalk talk){
    }
    public void deleteFromDatabase(RememRecord rem){
        //String s=rem.getTitle()+rem.getContent()+Integer.toString(rem.getId());
        //Toast.makeText(MainActivity.this, "删除"+s, Toast.LENGTH_SHORT).show();
        dbHelper = new MyDatabaseHelper(MainActivity.this,"TestTalk.db",null,2);//数据库
        db=dbHelper.getWritableDatabase();
        int id=rem.getId();
        db.delete("forget","id=?",new String[]{Integer.toString(id)});
        db.close();
    }
    public void insertIntoChildTalkDatabase(Msgtalk talk){

    }
    //备忘事项管理，闹铃相关
    public void addAlet(long time,String title,String content){
        Toast.makeText(MainActivity.this,"添加闹钟",Toast.LENGTH_SHORT).show();
        Intent i = new Intent(MainActivity.this,AlarmService.class);
        i.putExtra("time",(int)time);
        i.putExtra("title",title);
        i.putExtra("content",content);
        PendingIntent pi= PendingIntent.getService(MainActivity.this,(int)time,i,0);//编号time
        manager.set(AlarmManager.RTC_WAKEUP,time,pi);
    }
    public void cancelAlert(long time){
        Toast.makeText(MainActivity.this,"删除闹钟",Toast.LENGTH_SHORT).show();
        Intent i = new Intent(MainActivity.this,AlarmService.class);
        PendingIntent pi= PendingIntent.getService(MainActivity.this,(int)time,i,0);//编号time
        manager.cancel(pi);
    }

    //生命周期相关函数
    @Override
    protected void onResume() {
        super.onResume();
    }
    @Override
    protected void onStart() {
        super.onStart();
        //获取当前时间
    }
    @Override
    protected void onPause() {
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        //Toast.makeText(MainActivity.this,"Main关闭",Toast.LENGTH_LONG).show();
        if(!setTraceServer){
            Intent stopIntent=new Intent(MainActivity.this,TraceService.class);
            stopService(stopIntent);
        }
        if(isLogin) {
            unbindService(connection);
        }
        super.onDestroy();
    }

}
